<?php

namespace pmvc;
use pmvc\ClassLoader;

use Exception;

/**
 * Basic implementation of the {@link ClassLoader}
 * interface that uses the file system to load
 * classes.
 *
 */
class FileSystemClassLoader
	implements ClassLoader {

	private $classPath = Array();

	/**
	 * Creates the {@link FileSystemClassLoader} and configures
	 * it for loading classes from the given classpath.
	 * @param $classPath an array of class paths
	 */
	public function __construct($classPath) {
		if (is_array($classPath)) {
			foreach ($classPath as $cp) {
				$this->addToClassPath($cp);
			}
		} else if (is_string($classPath)) {
			$this->addToClassPath($classPath);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	function requireFile($file) {
		$file = str_replace("\\", "/", $file);
		if (substr($file, 0, 1)!="/") {
			$file = "/".$file;
		}
	    foreach ($this->classPath as $dir) {
	    	$f = $dir.$file;
	        if (file_exists($f)===TRUE) {
	        	require($f);
	            return TRUE;
	        }
	    }
	    return FALSE;
	}

	/**
	 * {@inheritDoc}
	 */
	function loadClass($className) {
		$className = str_replace("\\", "/", $className);
		return $this->requireFile($className.".class.php");
	}

	/**
	 * Adds an entry to the class path.
	 * @param string $path the path
	 */
	function addToClassPath($path) {
		if (!file_exists($path)) {
			throw new Exception("Path doesn't exist: ".$path);
		} else if (!is_dir($path)) {
			throw new Exception("Path is not a directory: ".$path);
		}
		array_push($this->classPath, str_replace("\\", "/", realpath($path)));
	}
}


?>